from django.db.models import get_model
from django.conf import settings
from django.http import HttpResponse, Http404

from FeatureServer.DataSource.PostGIS import PostGIS
from FeatureServer.Server import Server

__all__ = ["feature"]

server = Server({})

sources = {}

def feature(request, app, model, object, format):
	"""
	Simple wrapper around FeatureServer. We only support
	PostGIS at the moment.
	"""
	name = ("%s.%s" % (app, model)).lower()
	if name not in server.datasources:
		model = get_model(app, model)
		if not model:
			raise Http404
		dsn = "dbname=%s" % settings.DATABASE_NAME
		if settings.DATABASE_HOST:
			dsn = dsn + " host=%s" % settings.DATABASE_HOST
		if settings.DATABASE_PORT:
			dsn = dsn + " port=%s" % settings.DATABASE_PORT
		if settings.DATABASE_USER:
			dsn = dsn + " user=%s" % settings.DATABASE_USER
		if settings.DATABASE_PASSWORD:
			dsn = dsn + " password=%s" % settings.DATABASE_PASSWORD
		unused, fid = model._meta.pk.get_attname_column()
		if hasattr(model, "geometry") and isinstance(model.geometry, str):
			geometry = model.geometry
		else:
			geometry = "geometry"
		args = {
			'layer' : model._meta.db_table,
			'dsn' : dsn,
			'fid' : fid,
			'geometry' : geometry,
			'writable' : False
			}
		backend = PostGIS(name, **args)
		server.datasources[name] = backend

	## a bit kludgy, synthesize arguments to featureserver
	params = {} 
	path_info = "/" + name + "/" + object + "." + format
	host = "http://localhost/"

	try:
		content_type, data = server.dispatchRequest(params, path_info, host)
	except TypeError:
		## another kludge -- this happens when there are no
		## results from the PostGIS back-end -- see PostGIS.py
		## line 208
		raise Http404

	response = HttpResponse()
	response["Content-Type"] = content_type
	response.write(data)
	return response
